﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AddIn.EA.Architecture.CatalogService.BusinessEntity;
using AddIn.EA.Architecture.CatalogService.BusinessLogic;
using System.IO;
using System.Xml.Serialization;
using AddIn.EA.Core.Common;
using AddIn.EA.Core.Interface;
using AddIn.EA.Framework;
using AddIn.EA.Framework.Common;
using System.Text.RegularExpressions;
using AddIn.EA.Architecture.Validation.Presentation;

namespace AddIn.EA.Architecture.CatalogService.Presentation
{
    [AddInMenu("Gerar XML do Catálogo de Serviços")]
    public partial class frmCatalogXML : Form, IAddInArchitecture
    {
        private RepositoryManager repository { get; set; }
        private IElement selectedElement { get; set; }

        public frmCatalogXML()
        {
            InitializeComponent();
        }

        #region IAddInArchitecture Members

        public bool CheckState(EA_Application.Repository repository, MenuLocation menuLocation)
        {
            this.repository = RepositoryManager.LoadManager(repository);

            this.selectedElement = this.repository.GetSelectedObject();

            bool showForm = CheckShowForm(selectedElement, menuLocation);

            if (!showForm)
                MessageBox.Show("O add-in selecionado deve ser executado apenas no namespace Service", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            return showForm;
        }

        public void Execute(EA_Application.Repository repository, MenuLocation menuLocation)
        {
            this.ShowDialog();
        }

        #endregion

        private void btnGerarXml_Click(object sender, EventArgs e)
        {
            Cursor oldCursor = Cursor.Current;

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                this.txtXml.Clear();

                if (ckbSalvarArquivo.Checked)
                {
                    if (string.IsNullOrEmpty(txtPathXml.Text.Trim()))
                        throw new CatalogServiceException("Favor informar uma pasta para o XML");
                    if (!IsValidFilePath(txtPathXml.Text))
                        throw new CatalogServiceException("Favor informar uma pasta válida para o XML");
                }

                if (string.IsNullOrEmpty(txtPathAssembly.Text.Trim()))
                    throw new CatalogServiceException("Favor informar uma pasta que contenha o assembly");
                if (!IsValidFilePath(txtPathAssembly.Text))
                    throw new CatalogServiceException("Favor informar uma pasta válida que contenha o assembly");

                string xml = string.Empty;
                var bl = new BusinessLogic.CatalogXML(this.repository, (Package)this.selectedElement);
                var errors = bl.CreateXML(ckbSalvarArquivo.Checked, txtPathXml.Text, txtPathAssembly.Text, out xml);

                    var validationDialog = new frmValidateSummary();
                    if (!validationDialog.ShowSummary(errors, true))
                        this.txtXml.Text = xml;
            }
            catch (CatalogServiceException ex)
            {
                MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = oldCursor;
            }
        }

        private void frmXMLComments_FormClosing(object sender, FormClosingEventArgs e)
        {
            txtXml.Clear();
            e.Cancel = true;
            this.Hide();
        }

        private void ckbSalvarArquivo_CheckedChanged(object sender, EventArgs e)
        {
            EnableFolderPicker(ckbSalvarArquivo.Checked);

            if (ckbSalvarArquivo.Checked)
                MessageBox.Show(@"Verifique antes se o XML escolhido está atualizado e com CheckOut para o seu usuário", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnEscolherPasta_Click(object sender, EventArgs e)
        {
            var pickFolder = new FolderBrowserDialog();
            pickFolder.SelectedPath = txtPathXml.Text;
            if (pickFolder.ShowDialog() == DialogResult.OK)
                txtPathXml.Text = pickFolder.SelectedPath;
        }

        private void btnEscolherPastaAssembly_Click(object sender, EventArgs e)
        {
            var pickFolder = new FolderBrowserDialog();
            pickFolder.SelectedPath = txtPathAssembly.Text;
            if (pickFolder.ShowDialog() == DialogResult.OK)
                txtPathAssembly.Text = pickFolder.SelectedPath;
        }


        private bool CheckShowForm(IElement selectedElement, MenuLocation location)
        {
            return (selectedElement is AddIn.EA.Framework.Package &&
                    selectedElement.Name == "Service")
                    &&
                   (location == AddIn.EA.Core.Common.MenuLocation.MainMenu ||
                    location == AddIn.EA.Core.Common.MenuLocation.TreeView);
        }

        private void EnableFolderPicker(bool enable)
        {
            txtPathXml.Enabled = enable;
            btnEscolherPastaXml.Enabled = enable;
        }

        /// <summary>
        /// method to determine is the absolute file path is a valid path
        /// </summary>
        /// <param name="path">the path we want to check</param>
        public bool IsValidFilePath(string path)
        {
            string pattern = @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$";
            Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return reg.IsMatch(path);
        }

    }
}
